package org.jgs1904.tieba.controller;

import lombok.extern.slf4j.Slf4j;
import org.jgs1904.tieba.entity.Comment;
import org.jgs1904.tieba.entity.Post;
import org.jgs1904.tieba.entity.User;
import org.jgs1904.tieba.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author junki
 * @date 2020/5/12 14:42
 */
@Controller
@RequestMapping("comment")
@Slf4j
public class CommentController {

    @Autowired
    private CommentService commentService;

    @RequestMapping("add")
    public String add(Comment comment, Long postId, @SessionAttribute("onlineUser") User user, RedirectAttributes redirectAttributes) {

        if (user == null) {
            redirectAttributes.addAttribute("message", "你还没有登录！");
        } else {
            comment.setUser(user);
            comment.setPost(Post.builder().id(postId).build());
        }

        Comment result = commentService.add(comment);

        if (result == null) {
            redirectAttributes.addAttribute("message", "评论错误，请稍后重试！");
            redirectAttributes.addAttribute("comment", comment);
        } else {
            redirectAttributes.addAttribute("message", "评论成功！");
        }

        redirectAttributes.addAttribute("id", postId);

        return "redirect:/post/detail";
    }

}
